package examples.ejb.ejb20.basic.transaction;

import java.rmi.RemoteException;
import java.util.Hashtable;
import javax.ejb.CreateException;
import javax.ejb.RemoveException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * This class illustrates calling a stateless Session Bean and performing
 * the following exercises:
 * <ul>
 * <li> Create a Trader
 * <li> Buy some shares using the Trader
 * <li> Sell some shares using the Trader
 * <li> Remove the Trader
 * </ul>
 *
 * @author Copyright (c) 1998-2008 by BEA Systems, Inc. All Rights Reserved.
 */
public class Client
{
  private static final String JNDI_NAME = "ejb20-transaction-TransactionHome";
  private String url;
  private TransactionHome home;
  //private static List<String[]> listOfNames = new ArrayList<String[]>();

  public Client(String url) throws NamingException {
    this.url = url;
    home = lookupHome();
  }

  /**
   * Runs this example from the command line. Example:
   * <p>
   * <tt>java examples.ejb.ejb20.basic.transaction.Client "t3://localhost:7001"</tt>
   * <p>
   * The parameters are optional, but if any are supplied,
   * they are interpreted in this order:
   * <p>
   * @param args               URL such as "t3://localhost:7001" of Server
   */
  public static void main(String[] args) throws Exception {
    log("\nBeginning transaction.Client...\n");
    String url       = "t3://localhost:7001";
    Client client = null;

    // Parse the argument list
     if (args.length > 1) {
      log("Usage: java examples.ejb.ejb20.basic.transaction.Client t3://hostname:port");
      return;
    } else if (args.length == 1) {
      url = args[0];
    }

    try {
      client = new Client(url);
      client.example();
    } catch (NamingException ne) {
      log("Unable to look up the beans home: " + ne.getMessage());
      throw ne;
    } catch (Exception e) {
      log("There was an exception while creating and using Transaction.");
      log("This indicates that there was a problem communicating with the server: "+e);
      throw e;
    }

    log("\nEnd transaction.Client...\n");
  }

  /**
   * Runs this example.
   */
  public void example()
    throws CreateException, RemoteException, RemoveException
  {
    // create a Trader
    log("Performing Transaction");
    Transaction transaction = (Transaction) narrow(home.create(), Transaction.class);
    String line="";
    try {
	BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(
			new FileInputStream("C:/bea/wlserver_10.3/transaction_input.txt"))));	
	
		while ((line=reader.readLine())!=null){
			transaction.addRequest(line);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}

	System.out.println("Sample Record items:");
	System.out.println(transaction.getTitle(2));
	System.out.println(transaction.getName(2));
	System.out.println(transaction.getQuantity(2));
	System.out.println(transaction.getAddress(2));
	System.out.println(transaction.getOrganization(2));
	
	// remove the Trader
    log("Removing Transaction");
    transaction.remove();
  }

  /**
   * RMI/IIOP clients should use this narrow function
   */
  private Object narrow(Object ref, Class c) {
    return PortableRemoteObject.narrow(ref, c);
  }

//	private static void readTheInputFile() throws FileNotFoundException {
//		String line=null;
//		Pattern extPattern=Pattern.compile("(\\w*)\\*(\\w*)\\*",Pattern.CASE_INSENSITIVE);
//		
//		BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(
//				new FileInputStream("C:/bea/wlserver_10.3/transaction_input.txt"))));	
//		try {
//			while ((line=reader.readLine())!=null){
//				Matcher matcher = extPattern.matcher(line.trim());
//				while (matcher.find()){
//					String[] newRec = new String[2];
//					newRec[0]= matcher.group(1);
//					newRec[1]= matcher.group(2);
//					listOfNames.add(newRec);
//				}
//			}		
//		} catch (NumberFormatException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}

  
  
  /**
   * Lookup the EJBs home in the JNDI tree
   */
  private TransactionHome lookupHome() throws NamingException {
    // Lookup the beans home using JNDI
    Context ctx = getInitialContext();
    try {
      Object home = ctx.lookup(JNDI_NAME);
      return (TransactionHome) narrow(home, TransactionHome.class);
    } catch (NamingException ne) {
      log("The client was unable to lookup the EJBHome.  Please make sure ");
      log("that you have deployed the ejb with the JNDI name "+
        JNDI_NAME+" on the WebLogic server at "+url);
      throw ne;
    }
  }

  /**
   * Using a Properties object will work on JDK 1.1.x and Java2
   * clients
   */
  private Context getInitialContext() throws NamingException {
    
    try {
      // Get an InitialContext
      Hashtable<String,String> h = new Hashtable<String,String>();
      h.put(Context.INITIAL_CONTEXT_FACTORY,
        "weblogic.jndi.WLInitialContextFactory");
      h.put(Context.PROVIDER_URL, url);
      return new InitialContext(h);
    } catch (NamingException ne) {
      log("We were unable to get a connection to the WebLogic server at "+url);
      log("Please make sure that the server is running.");
      throw ne;
    }
  }

  private static void log(String s) { System.out.println(s); }
  
}
